import util from "@/libs/util.js";
import * as HttpServices from "@/api/HttpServices";
import dayjs from "dayjs";
import * as CryptoJS from "crypto-js";
import storage from "@/utils/storage";

export default {
  namespaced: true,
  state: {
    token: util.cookies.get("token"),
    accountList: [],
    weight_format: storage.getStorage("weight_format") || 4,
    userInfo: storage.getStorage("userInfo")
  },
  mutations: {
    SET_USERINFO: (state, userInfo) => {
      if (userInfo) {
        userInfo.institutional_id = userInfo.institutional_id ? userInfo.institutional_id.toString() : userInfo.institutional_id;
        userInfo.department_id = userInfo.department_id ? userInfo.department_id.toString() : userInfo.department_id;
        userInfo.business_unit_id = userInfo.business_unit_id ? userInfo.business_unit_id.toString() : userInfo.business_unit_id;
        userInfo.emp_id = userInfo.emp_id ? userInfo.emp_id.toString() : userInfo.emp_id;
        state.weight_format = userInfo.weight_format || 4;
        storage.setStorage("weight_format", userInfo.weight_format || 4);
      }
      storage.setStorage("userInfo", userInfo);
      state.userInfo = userInfo;
    }
  },
  actions: {
    /**
     * @description 登录
     * @param {Object} param context
     * @param {Object} param vm {Object} vue 实例
     * @param {Object} param username {String} 用户账号
     * @param {Object} param password {String} 密码
     * @param {Object} param route {Object} 登录成功后定向的路由对象 任何 vue-router 支持的格式
     */
    async LoginByUsername({ commit, dispatch }, { vm, username, password }) {
      const dateStr = dayjs().format("YYYYMMDD");
      const _password = CryptoJS.MD5("ddmg!@168" + dateStr + CryptoJS.MD5(password).toString()).toString();
      const transCode = "U20001i0";
      const body = {
        username,
        password: _password,
        group: 1
      };
      const res = await HttpServices.startApiReq(transCode, body);
      if (res.code === 200) {
        if (res.data.isLogin === 2) {
          return { isLogin: 2, empList: res.data.empList };
        } else {
          // 非企业员工
          let userInfo = res.data.user;
          let companyCodeNo = () => {
            util.cookies.set("uuid", username);
            util.cookies.set("token", res.data.token);
            // util.cookies.set("PHPSESSID", "4ojdgik64r1lomp4mf53nnnkl5");
            let userName = (userInfo && userInfo.name) || "";
            dispatch("d2admin/user/set", { name: userName }, { root: true });
            // 用户登录后从持久化数据加载一系列的设置
            dispatch("load");
            vm.$router.push({ path: "/" });
          };
          commit("SET_USERINFO", userInfo);
          if (userInfo && userInfo.company_code === undefined) {
            vm.$message.warning("您还没有加入任何企业！");
          } else {
            let { institutional_active_state, member_type } = userInfo || {};
            // 如果是试用会员，并且已到期
            if (institutional_active_state == 2 && member_type == 2) {
              vm.$message.error("您的企业试用会员已经到期，请及时续费！");
              return;
            }
            // 如果是正式会员，并且已到期
            if (institutional_active_state == 2 && member_type == 1) {
              vm.$message({
                showClose: true,
                message: "您的企业会员已经到期，请及时续费（目前只有查看权限）",
                type: "warning",
                onClose() {
                  companyCodeNo();
                }
              });
              return;
            }
            companyCodeNo();
          }
        }
      }
    },

    async selectByAccount({ commit, dispatch }, { vm, payload }) {
      console.log("selectByAccount in action");

      // 将从服务器端拿到的token（唯一标示用户身份）放到浏览器本地Cookie中去
      const transCode = "U2000100";
      const body = {
        emp_id: payload.id,
        username: payload.username
      };
      const res = await HttpServices.startApiReq(transCode, body);
      if (res.code === 200) {
        commit("SET_USERINFO", res.data.user);
        util.cookies.set("uuid", res.data.token);
        util.cookies.set("token", res.data.token);
        // util.cookies.set("PHPSESSID", "4ojdgik64r1lomp4mf53nnnkl5");

        dispatch("d2admin/user/set", { name: res.data.user.company_name || res.data.user.name }, { root: true });
        dispatch("load");
        vm.$router.push({ path: "/" });
      }
    },

    logout({ commit, dispatch }) {
      try {
        HttpServices.startApiReq("U2000101")
          .then(res => {
            commit("d2admin/gray/set", false, { root: true });
            util.cookies.remove("token");
            util.cookies.remove("uuid");
            dispatch("d2admin/user/set", {}, { root: true });
            commit("d2admin/menu/remoteMenuSet", null, { root: true });
            dispatch("d2admin/page/clearAll", {}, { root: true });
            if (res.code === 200) {
              return Promise.resolve(0);
            } else {
              return Promise.resolve(1);
            }
          })
          .catch(e => {
            commit("d2admin/gray/set", false, { root: true });
            util.cookies.remove("token");
            util.cookies.remove("uuid");
            dispatch("d2admin/user/set", {}, { root: true });
            commit("d2admin/menu/remoteMenuSet", null, { root: true });
            dispatch("d2admin/page/clearAll", {}, { root: true });
            return Promise.resolve(1);
          });
      } catch (e) {
        console.log(e);
        return Promise.resolve(1);
      }
    },

    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} state vuex state
     */
    load({ commit, dispatch }) {
      return new Promise(async resolve => {
        // DB -> store 加载用户名
        await dispatch("d2admin/user/load", null, { root: true });
        // DB -> store 加载主题
        await dispatch("d2admin/theme/load", null, { root: true });
        // DB -> store 加载页面过渡效果设置
        await dispatch("d2admin/transition/load", null, { root: true });
        // DB -> store 持久化数据加载上次退出时的多页列表
        await dispatch("d2admin/page/openedLoad", null, { root: true });
        // DB -> store 持久化数据加载侧边栏折叠状态
        await dispatch("d2admin/menu/asideCollapseLoad", null, { root: true });
        // DB -> store 持久化数据加载全局尺寸
        await dispatch("d2admin/size/load", null, { root: true });
        // end
        resolve();
      });
    }
  }
};
